package com.qmhl.toolposition.fragment

import android.app.AlertDialog
import android.app.ProgressDialog
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.hjq.toast.Toaster
import com.lxj.xpopup.XPopup
import com.qmhl.toolposition.R
import com.qmhl.toolposition.activity.AgreementActivity
import com.qmhl.toolposition.activity.AppUpdatePopup
import com.qmhl.toolposition.activity.FeedbackActivity
import com.qmhl.toolposition.activity.PositionHelperActivity
import com.qmhl.toolposition.activity.VerifiCodeLoginActivity
import com.qmhl.toolposition.activity.VipActivity
import com.qmhl.toolposition.api.UserService
import com.qmhl.toolposition.api.content.AppUpdate
import com.qmhl.toolposition.api.content.ShareInfo
import com.qmhl.toolposition.databinding.DialogAccountCancellationBinding
import com.qmhl.toolposition.databinding.FragmentAppMineBinding
import com.qmhl.toolposition.event.LoginEvent
import com.qmhl.toolposition.event.TabSelectEvent
import com.qmhl.toolposition.utils.PUtils
import com.qmhl.toolposition.utils.PreferenceUtil
import com.qmhl.toolposition.utils.UpdateUtils
import com.qmhl.toolposition.utils.umeng.AuthPageConfig
import com.qmhl.toolposition.utils.umeng.BaseUIConfig
import com.qmhl.toolposition.utils.umeng.Constant
import com.qmhl.toolposition.utils.umeng.HttpUtil
import com.umeng.commonsdk.utils.UMUtils
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import com.umeng.umverify.UMResultCode
import com.umeng.umverify.UMVerifyHelper
import com.umeng.umverify.listener.UMTokenResultListener
import com.umeng.umverify.model.UMTokenRet
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONException
import org.json.JSONObject


class AppMineFragment : Fragment() {

    private var TAG = "AppMineFragment"

    /**
     * 友盟
     * **/
    private var mTvResult: String? = null
    private var mPhoneNumberAuthHelper: UMVerifyHelper? = null
    private var mProgressDialog: ProgressDialog? = null
    private var mTokenResultListener: UMTokenResultListener? = null
    private var mUIType: Constant.UI_TYPE? = null
    private var mUIConfig: AuthPageConfig? = null

    private lateinit var binding: FragmentAppMineBinding
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        binding = FragmentAppMineBinding.inflate(inflater, container, false)
        initData()
        initListener()
        return binding.root
    }

    private fun initListener() {

        binding.llShare.setOnClickListener {

            shareWEchat()

        }

        //意见反馈
        binding.llFeedback.setOnClickListener {
            startActivity(Intent(context, FeedbackActivity::class.java))
        }

        //定位设置
        binding.llPositionSetting.setOnClickListener {
            startActivity(Intent(context, PositionHelperActivity::class.java))
        }

        //开通vip
        binding.llVipContainer.setOnClickListener {
            startActivity(Intent(context, VipActivity::class.java))
        }

        //登录
        binding.ivLogin.setOnClickListener {

            oneKeyLogin()

        }

        //用户协议
        binding.llUserAgreement.setOnClickListener {
            val intent = Intent(context, AgreementActivity::class.java).apply {
                putExtra("url", PUtils.Config.userAgreement_assert)
                putExtra("title", PUtils.Config.userAgreement_title)
            }
            startActivity(intent)
        }

        //隐私协议
        binding.llPrivacyAgreement.setOnClickListener {
            val intent = Intent(context, AgreementActivity::class.java).apply {
                putExtra("url", PUtils.Config.privacyAgreement_assert)
                putExtra("title", PUtils.Config.privacyAgreement_title)
            }
            startActivity(intent)
        }

        //会员协议
        binding.llPayAgreement.setOnClickListener {
            val intent = Intent(context, AgreementActivity::class.java).apply {
                putExtra("url", PUtils.Config.payAgreement_assert)
                putExtra("title", PUtils.Config.payAgreement_title)
            }
            startActivity(intent)
        }

        //永久销户
        binding.llAccountCancellation.setOnClickListener {
            accountCancellation()
        }

        //退出登录
        binding.btnExitLogin.setOnClickListener {

            showExitLoginDialog()
        }

        //版本号
        binding.llVersion.setOnClickListener {
            updateApp()
        }
    }

    private fun shareWEchat() {

        var dialog = XPopup.Builder(context)
            .asLoading("正在为您分享")

        dialog.show()

        lifecycleScope.launch {
            var content = UserService.create()
                .shareInfo()
            if (content.code == 200) {
                dialog.dismiss()
                val data = content.data
                goShare(data)
            } else {
                Toaster.showShort(content.msg)
            }
        }


    }


    private fun goShare(data: ShareInfo) {
        val web: UMWeb =
            UMWeb(data.shareLink)
        web.title = "爱守护足迹" //标题
        val image: UMImage = UMImage(
            activity,
            data.shareImg
        ) //网络图片

        web.setThumb(image) //缩略图

        web.description = data.shareDesc //描述


        ShareAction(activity)
            .withMedia(web)
            .setCallback(object : UMShareListener {
                override fun onStart(p0: SHARE_MEDIA?) {

                }

                override fun onResult(p0: SHARE_MEDIA?) {

                }

                override fun onError(p0: SHARE_MEDIA?, p1: Throwable?) {

                }

                override fun onCancel(p0: SHARE_MEDIA?) {

                }
            })
            .setDisplayList(
                SHARE_MEDIA.WEIXIN,
                SHARE_MEDIA.WEIXIN_CIRCLE,
                SHARE_MEDIA.WEIXIN_FAVORITE
            )
            .open()
    }


    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public fun onLoginEvent(event: LoginEvent) {
        oneKeyLogin()
    }

    /**
     * 进入app就需要登录的场景使用
     */
    private fun oneKeyLogin() {
        if (!PreferenceUtil.isLogin()) {
            mPhoneNumberAuthHelper =
                UMVerifyHelper.getInstance(context, mTokenResultListener)
            mUIConfig!!.configAuthPage()
            getLoginToken(5000)
        }

    }


    /**
     * 拉起授权页
     *
     * @param timeout 超时时间
     */
    fun getLoginToken(timeout: Int) {
        mPhoneNumberAuthHelper!!.getLoginToken(context, timeout)
        showLoadingDialog("正在唤起授权页")
    }

    fun accountCancellation() {
        var login = PreferenceUtil.isLogin()
        if (!login) {
            Toaster.showShort(PUtils.Toast.PLEASE_LOGIN)
            return
        }
        showAccountCancellationDialog()

    }

    fun showLoadingDialog(hint: String?) {
        if (mProgressDialog == null) {
            mProgressDialog = ProgressDialog(context)
            mProgressDialog!!.setProgressStyle(ProgressDialog.STYLE_SPINNER)
        }
        mProgressDialog!!.setMessage(hint)
        mProgressDialog!!.setCancelable(true)
        mProgressDialog!!.show()
    }


    private fun showAccountCancellationDialog() {
        val binding: DialogAccountCancellationBinding =
            DialogAccountCancellationBinding.inflate(layoutInflater)
        val dialog = AlertDialog.Builder(context).run {
            setCancelable(false)
            setView(binding.root)
            create()
        }

        dialog.show()
        binding.tvCancel.setOnClickListener {
            dialog.dismiss()
        }
        binding.tvOk.setOnClickListener {
            dialog.dismiss()
            Toaster.showShort(PUtils.Toast.ACCOUNT_CANCEL)
        }

    }

    private fun showExitLoginDialog() {
        XPopup.Builder(context).asConfirm(
            "退出登录提示", "您是否要退出登录?"
        ) {
            PreferenceUtil.exitLogin()
            onResume()
            Toaster.showShort("退出成功")
        }
            .show()


    }


    private fun initData() {
        EventBus.getDefault().register(this)
        sdkInit()
        mUIType = Constant.UI_TYPE.FULL_PORT
        mUIConfig = BaseUIConfig.init(mUIType, activity, mPhoneNumberAuthHelper)

    }

    override fun onResume() {
        super.onResume()
        val currentUser = PreferenceUtil.getCurrentUser()
        binding.tvUsername.text = currentUser.username
        mUIConfig!!.onResume()


        if (!currentUser.isLogin) {
            binding.btnExitLogin.visibility = View.INVISIBLE


        } else {
            binding.btnExitLogin.visibility = View.VISIBLE
            context?.let {
                Glide.with(it).load(R.mipmap.login_users)
                    .into(binding.ivLogin)
            }
        }
    }


    fun sdkInit() {
        mTokenResultListener = object : UMTokenResultListener {
            override fun onTokenSuccess(s: String) {
                hideLoadingDialog()
                var tokenRet: UMTokenRet? = null
                try {
                    tokenRet = UMTokenRet.fromJson(s)
                    if (UMResultCode.CODE_START_AUTHPAGE_SUCCESS == tokenRet.code) {
                        Log.i("TAG", "唤起授权页成功：$s")
                    }
                    if (UMResultCode.CODE_GET_TOKEN_SUCCESS == tokenRet.code) {
                        Log.i("TAG", "获取token成功：$s")
                        getResultWithToken(tokenRet.token)
                        mUIConfig!!.release()
                        //登录质量分
                        val token = tokenRet.token
                        Thread {
                            val jo = JSONObject()
                            try {
                                jo.putOpt("token", token)
                                jo.putOpt("appkey", UMUtils.getAppkey(context))
                                jo.putOpt(
                                    "verifyId",
                                    mPhoneNumberAuthHelper!!.getVerifyId(context)
                                )
                                val message: String =
                                    HttpUtil.postRequest(
                                        "https://ai.login.umeng.com/api/demo/info",
                                        jo
                                    )
                                Log.d("jessie", "获取登录质量分$message")
                            } catch (e: JSONException) {
                            }
                        }.start()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            override fun onTokenFailed(s: String) {
                Log.e(TAG, "获取token失败：$s")
                hideLoadingDialog()
                var tokenRet: UMTokenRet? = null
                mPhoneNumberAuthHelper!!.quitLoginPage()
                try {
                    tokenRet = UMTokenRet.fromJson(s)
                    if (UMResultCode.CODE_ERROR_USER_CANCEL == tokenRet!!.getCode()) {
                        //模拟的是必须登录 否则直接退出app的场景

                    } else {


                        startCodeActivity()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                mUIConfig!!.release()
            }
        }
        mPhoneNumberAuthHelper = UMVerifyHelper.getInstance(context, mTokenResultListener)
    }

    private fun startCodeActivity() {
        val pIntent =
            Intent(context, VerifiCodeLoginActivity::class.java)
        startActivityForResult(pIntent, 1002)
    }


    fun hideLoadingDialog() {
        if (mProgressDialog != null) {
            mProgressDialog!!.dismiss()
        }
    }

    fun getResultWithToken(token: String?) {

        lifecycleScope.launch {
            var content = UserService.create()
                .oneKeyLogin(token)

            var code = content.code
            if (code != 200) {
                val pIntent =
                    Intent(context, VerifiCodeLoginActivity::class.java)
                startActivity(pIntent)
            } else {
                var phoneNumber = content.data.phone
                var token = content.data.token
                if (phoneNumber != null) {
                    Toaster.showShort(PUtils.Toast.LOGIN_SUCCESS)
                    //退出授权页面
                    mPhoneNumberAuthHelper!!.quitLoginPage()
                    PreferenceUtil.saveCurrentUser(phoneNumber, token)

                } else {
                    val pIntent =
                        Intent(context, VerifiCodeLoginActivity::class.java)
                    startActivity(pIntent)
                }
            }


        }
//        ExecutorManager.run(Runnable {
//            val result: String = MockRequest.getPhoneNumber(token)
//            requireActivity().runOnUiThread {
//                mTvResult = "登陆成功：$result"
//                mPhoneNumberAuthHelper!!.quitLoginPage()
//            }
//        })
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1002) {
            if (resultCode == 1) {
                mTvResult = "登陆成功：" + data!!.getStringExtra("result")
            } else {
                //模拟的是必须登录 否则直接退出app的场景


            }

        }
    }

    private fun updateApp() {

        var versionName = UpdateUtils.getVersionName(context)
        val curVersion = versionName.toDouble()

        lifecycleScope.launch {
            var content = UserService.create()
                .updateInfo()
            if (content.code == 200) {
                val data = content.data
                isShowUpdate(curVersion, data)
            } else {
                Toaster.showShort(content.msg)
            }
        }


    }

    private fun isShowUpdate(curVersion: Double, data: AppUpdate) {
        if (data.version > curVersion) {

            var appUpdatePopup = context?.let { AppUpdatePopup(it, data.link, data.toast) }
            XPopup.Builder(context)
                .asCustom(appUpdatePopup)
                .show()
        }
    }


}